package cn.tedu.emp.service;

import cn.tedu.emp.common.utils.ExcelUtil;
import cn.tedu.emp.mapper.EmployeeMapper;
import cn.tedu.emp.pojo.Employee;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void download(HttpServletRequest request, HttpServletResponse response) {
        //获取数据
        List<Employee> list = employeeMapper.selectAll();
        //excel标题
        String[] title = {"ID","Name","Salary","Age"};
        //excel文件名
        String fileName = "员工表.xls";
        //sheet名
        String sheetName = "工作表1";
        // 存在问题：若名字为空，会报错，如何避免
        String[][] content = new String[list.size()][title.length];
        for (int i = 0; i < list.size(); i++) {
            content[i][0] = list.get(i).getId().toString();
            content[i][1] = list.get(i).getName().toString();
            content[i][2] = list.get(i).getSalary().toString();
            content[i][3] = list.get(i).getAge().toString();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端

        OutputStream os = null;
        try {
            ExcelUtil.setResponseHeader(response, fileName);
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
